package com.broada.apm.utils;

import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.StringUtils;
import org.apache.wink.client.ClientResponse;
import org.apache.wink.client.Resource;
import org.apache.wink.client.RestClient;

import com.broada.apm.Constants;

/**
 * 
 * restClient
 * 
 * @author louyi Create By 2014-11-21 上午10:56:20
 */
public class RestClientUtil {
	public static final String METHOD_GET = "GET";
	public static final String METHOD_PUT = "PUT";
	public static final String METHOD_DELETE = "DELETE";
	public static final String METHOD_POST = "POST";
	private static RestClient client = new RestClient(Constants.httpClientConfig);

	public static ClientResponse doAction(String action, String url, String entity) {
		if (StringUtils.endsWithIgnoreCase(METHOD_PUT, action))
			return put(url, entity, client);
		if (StringUtils.endsWithIgnoreCase(METHOD_POST, action))
			return post(url, entity, client);
		if (StringUtils.endsWithIgnoreCase(METHOD_DELETE, action))
			return delete(url, client);
		if (StringUtils.endsWithIgnoreCase(METHOD_GET, action))
			return get(url, client);
		return null;
	}

	private static ClientResponse post(String url, String entity, org.apache.wink.client.RestClient client) {
		Resource resource = client.resource(url);
		return resource.post(entity);
	}

	private static ClientResponse get(String url, org.apache.wink.client.RestClient client) {
		Resource resource = client.resource(url);
		return resource.get();
	}

	private static ClientResponse put(String url, String entity, org.apache.wink.client.RestClient client) {
		Resource resource = client.resource(url);
		resource.accept(MediaType.APPLICATION_JSON_TYPE).contentType(MediaType.APPLICATION_JSON_TYPE);
		return resource.put(entity);
	}

	private static ClientResponse delete(String url, org.apache.wink.client.RestClient client) {
		Resource resource = client.resource(url);
		return resource.delete();
	}

}
